#include "../include/config.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstdlib>

Config& Config::getInstance() {
    static Config instance;
    return instance;
}

bool Config::loadFromFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开配置文件: " << filename << std::endl;
        return false;
    }
    
    std::string line;
    while (std::getline(file, line)) {
        std::string key, value;
        if (parseLine(line, key, value)) {
            config_data_[key] = value;
        }
    }
    
    return true;
}

std::string Config::getString(const std::string& key, const std::string& default_value) {
    auto it = config_data_.find(key);
    return (it != config_data_.end()) ? it->second : default_value;
}

int Config::getInt(const std::string& key, int default_value) {
    std::string value = getString(key);
    if (value.empty()) {
        return default_value;
    }
    
    try {
        return std::stoi(value);
    } catch (const std::exception&) {
        std::cerr << "配置项 " << key << " 的值不是有效的整数: " << value << std::endl;
        return default_value;
    }
}

double Config::getDouble(const std::string& key, double default_value) {
    std::string value = getString(key);
    if (value.empty()) {
        return default_value;
    }
    
    try {
        return std::stod(value);
    } catch (const std::exception&) {
        std::cerr << "配置项 " << key << " 的值不是有效的浮点数: " << value << std::endl;
        return default_value;
    }
}

bool Config::getBool(const std::string& key, bool default_value) {
    std::string value = getString(key);
    if (value.empty()) {
        return default_value;
    }
    
    std::transform(value.begin(), value.end(), value.begin(), ::tolower);
    return (value == "true" || value == "1" || value == "yes" || value == "on");
}

void Config::setString(const std::string& key, const std::string& value) {
    config_data_[key] = value;
}

void Config::setInt(const std::string& key, int value) {
    config_data_[key] = std::to_string(value);
}

void Config::setDouble(const std::string& key, double value) {
    config_data_[key] = std::to_string(value);
}

void Config::setBool(const std::string& key, bool value) {
    config_data_[key] = value ? "true" : "false";
}

// AI相关配置
std::string Config::getDeepSeekAPIKey() const {
    auto it = config_data_.find("deepseek.api_key");
    if (it != config_data_.end() && !it->second.empty()) {
        return it->second;
    }
    const char* env_key = std::getenv("DEEPSEEK_API_KEY");
    return env_key ? std::string(env_key) : "";
}

std::string Config::getDeepSeekBaseURL() const {
    auto it = config_data_.find("deepseek.base_url");
    return (it != config_data_.end()) ? it->second : "https://api.deepseek.com/v1/chat/completions";
}

std::string Config::getAIModel() const {
    auto it = config_data_.find("ai.model");
    return (it != config_data_.end()) ? it->second : "deepseek-chat";
}

double Config::getAITemperature() const {
    std::string value = getString("ai.temperature", "0.7");
    try {
        return std::stod(value);
    } catch (const std::exception&) {
        return 0.7;
    }
}

int Config::getAIMaxTokens() const {
    std::string value = getString("ai.max_tokens", "2000");
    try {
        return std::stoi(value);
    } catch (const std::exception&) {
        return 2000;
    }
}

std::string Config::getAISystemPrompt() const {
    auto it = config_data_.find("ai.system_prompt");
    return (it != config_data_.end()) ? it->second : "You are an intelligent assistant specialized in helping users with searches and providing relevant information. Please answer user questions in a concise and accurate manner.";
}

// 服务器配置
int Config::getServerPort() const {
    std::string value = getString("server.port", "8080");
    try {
        return std::stoi(value);
    } catch (const std::exception&) {
        return 8080;
    }
}

std::string Config::getDatabasePath() const {
    auto it = config_data_.find("database.path");
    return (it != config_data_.end()) ? it->second : "cpp_search.db";
}

// 缓存配置
bool Config::isAICacheEnabled() const {
    std::string value = getString("ai.cache_enabled", "true");
    std::transform(value.begin(), value.end(), value.begin(), ::tolower);
    return (value == "true" || value == "1" || value == "yes" || value == "on");
}

int Config::getMaxCacheSize() const {
    std::string value = getString("ai.max_cache_size", "1000");
    try {
        return std::stoi(value);
    } catch (const std::exception&) {
        return 1000;
    }
}

std::string Config::trim(const std::string& str) const {
    size_t first = str.find_first_not_of(" \t\r\n");
    if (first == std::string::npos) {
        return "";
    }
    
    size_t last = str.find_last_not_of(" \t\r\n");
    return str.substr(first, last - first + 1);
}

bool Config::parseLine(const std::string& line, std::string& key, std::string& value) const {
    size_t equal_pos = line.find('=');
    if (equal_pos == std::string::npos) {
        return false;
    }
    
    key = trim(line.substr(0, equal_pos));
    value = trim(line.substr(equal_pos + 1));
    
    // 移除值两端的引号
    if (value.length() >= 2 && 
        ((value.front() == '"' && value.back() == '"') || 
         (value.front() == '\'' && value.back() == '\''))) {
        value = value.substr(1, value.length() - 2);
    }
    
    return true;
}

// const版本的辅助方法实现
std::string Config::getString(const std::string& key, const std::string& default_value) const {
    auto it = config_data_.find(key);
    return (it != config_data_.end()) ? it->second : default_value;
}

int Config::getInt(const std::string& key, int default_value) const {
    auto it = config_data_.find(key);
    if (it == config_data_.end()) {
        return default_value;
    }
    
    try {
        return std::stoi(it->second);
    } catch (const std::exception&) {
        std::cerr << "配置项 " << key << " 的值不是有效的整数: " << it->second << std::endl;
        return default_value;
    }
}

double Config::getDouble(const std::string& key, double default_value) const {
    auto it = config_data_.find(key);
    if (it == config_data_.end()) {
        return default_value;
    }
    
    try {
        return std::stod(it->second);
    } catch (const std::exception&) {
        std::cerr << "配置项 " << key << " 的值不是有效的浮点数: " << it->second << std::endl;
        return default_value;
    }
}

bool Config::getBool(const std::string& key, bool default_value) const {
    auto it = config_data_.find(key);
    if (it == config_data_.end()) {
        return default_value;
    }
    
    std::string value = it->second;
    std::transform(value.begin(), value.end(), value.begin(), ::tolower);
    return (value == "true" || value == "1" || value == "yes" || value == "on");
}
